import React, { useState, useImperativeHandle, useRef } from "react";

import { Spin, Modal, notification } from 'antd'
import {FCForm} from "@components";
import { session } from '@core'
import { auditModalFields } from '../config'
import { auditEmerMsg } from '@apis/massMsgApi'

const AuditModal = (props) => {
  const {
    auditModalRef,
    queryFormRef
  } = props
  const [open, setOpen] = useState(false)
  const [loading, setLoading] = useState(false)
  
  // 暴露给父组件的方法
  useImperativeHandle(auditModalRef, () => ({
    showModal: (data) => {
      session.set('msgCustMainId',data.msgCustMainId)
      setOpen(true)
    },
  }))

  const formRef = useRef("formRef")
  const formProps = {
    name:"modalForm",
    formRef,
    fields: auditModalFields,
    initialValues: {
      auditStatus: 'ReviewedSuccess',
    },
    onFinish: async (v) => {
      setLoading(true)
      const params = {
        ...v,
        msgCustMainId: session.get('msgCustMainId')
      }

      const { data, error } = await auditEmerMsg(params)
      setLoading(false)
      if (error) return

      notification.success({message:data});
      setOpen(false)
      queryFormRef.current?.submit?.() // 重新加载表格的数据
    },
    layoutProps: {
      layout: "horizonal",
    },
  };


  const handleOk = () => {
    formRef.current?.submit?.()
  };

  const handleCancel = () => {
    if (loading) return
    setOpen(false)
    session.remove('msgCustMainId')
  };
  
  return (
    <Modal
      title='审批'
      className='modal'
      open={open}
      onOk={handleOk}
      bodyStyle={{padding: '24px 24px 0'}}
      onCancel={handleCancel}
      maskClosable= {false}
      destroyOnClose={true}
      confirmLoading={loading}
    >
      <Spin spinning={loading}>
        <FCForm {...formProps}/>
      </Spin>
    </Modal>
  );
};

export default React.memo(AuditModal);
